package com.zyg.util;

import com.alibaba.fastjson.JSON;
import com.zyg.common.RedisKey;
import com.zyg.model.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;

/**
 * 通过用户请求的token获取用户的信息
 */

@Slf4j
@Component
public class UserInfoUtil {

    /**
     * 获取用户信息
     * @param
     * @return 用户信息
     */
    public static UserInfo getUser(){
        try{
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String token = request.getHeader("Access-token");
            if(StringUtils.isBlank(token)){
                token = request.getParameter("Access-token");
            }
            if(StringUtils.isBlank(token)){
                throw new RuntimeException("请求没有带token或者是token错误！！！");
            }
            UserInfo userInfo =  JWTUtil.getTokenDataInfo(token);
            return userInfo;
        }
        catch(Exception e){
            e.printStackTrace();
            throw new RuntimeException("请求没有带token或者是token错误！！！");
        }
    }

    /**
     * 保存的时候获取用户信息
     * @return
     */
    public static UserInfo getUserSaveInfo(){
        String token = "";
        UserInfo userInfo = null;
        try{
            userInfo = new UserInfo();
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            token = request.getHeader("Access-token");
            if(StringUtils.isBlank(token)){
                token = request.getParameter("Access-token");
            }
            if(StringUtils.isBlank(token)){
                log.error("token:{}",token);
                log.error("没有获取到用户信息");
                return userInfo;
            }
            userInfo =  JWTUtil.getTokenDataInfo(token);
            return userInfo;
        }
        catch(Exception e){
            log.error("token:{}",token);
            log.error("没有获取到用户信息,解析token异常");
            return userInfo;
        }
    }

}
